package com.j180.config;


import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.logging.log4j.Log4jImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import javax.xml.transform.Source;
import java.beans.BeanProperty;


@Configuration
@MapperScan("com.j180.dao")
//读取外部配置文件
@PropertySource("classpath:config/db.properties")
public class MyBatisConfig {

    @Value("${dbDirver}")
    private String driverClassName;
     @Value("${dburl}")
    private String url;
     @Value("${user}")
    private String userName;
     @Value("${pwd}")
    private String pwd;

    //1 注册数据源
    @Bean
    public DataSource  dataSource(){

        System.out.println(this.userName+"   "+this.pwd);

        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(this.driverClassName);
        druidDataSource.setUrl(this.url);
        druidDataSource.setUsername(this.userName);
        druidDataSource.setPassword(this.pwd);
        return druidDataSource;
    }

     //2 注册SqlSessionFactory
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        //读取映射文件
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("mapper/*.xml"));
        //设置别名
        factoryBean.setTypeAliasesPackage("com.j180.bean");
        //配置log4j
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setLogImpl(Log4jImpl.class);

        return factoryBean.getObject();
    }
    //配置事务管理器
    @Bean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

}
